package org.project.d.register.nacos;

import com.alibaba.boot.nacos.discovery.autoconfigure.AutoDeregisterException;
import com.alibaba.boot.nacos.discovery.properties.NacosDiscoveryProperties;
import com.alibaba.boot.nacos.discovery.properties.Register;
import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

/**
 * @author lin
 * @version V1.0
 * @description
 * @date 2020/9/23 4:07 下午
 */
@Component
public class NacosDiscoveryAutoDeregister implements ApplicationListener<ContextClosedEvent> {

    private static final Logger logger = LoggerFactory
            .getLogger(NacosDiscoveryAutoRegister.class);

    @NacosInjected
    private NamingService namingService;

    private final NacosDiscoveryProperties discoveryProperties;
    private final NacosDiscoveryAutoRegister nacosDiscoveryAutoRegister;

    @Value("${spring.application.name:}")
    private String applicationName;

    public NacosDiscoveryAutoDeregister(NacosDiscoveryProperties discoveryProperties,
                                        NacosDiscoveryAutoRegister nacosDiscoveryAutoRegister) {
        this.discoveryProperties = discoveryProperties;
        this.nacosDiscoveryAutoRegister=nacosDiscoveryAutoRegister;
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        if (!discoveryProperties.isAutoRegister()) {
            return;
        }
        try {
            RegisterServer registerServer = nacosDiscoveryAutoRegister.getRegisterServer();

            Register tcpRegister = registerServer.getTcpRegister();
            if (tcpRegister !=null){
                namingService.deregisterInstance(tcpRegister.getServiceName(), tcpRegister.getGroupName(),
                        tcpRegister);
                logger.info("Finished auto deregister service : {}, ip : {}, port : {}",
                        tcpRegister.getServiceName(), tcpRegister.getIp(), tcpRegister.getPort());
            }

            Register udpRegister = registerServer.getUdpRegister();
            if (udpRegister !=null){
                namingService.deregisterInstance(udpRegister.getServiceName(), udpRegister.getGroupName(),
                        udpRegister);
                logger.info("Finished auto deregister service : {}, ip : {}, port : {}",
                        udpRegister.getServiceName(), udpRegister.getIp(), udpRegister.getPort());
            }
        }
        catch (NacosException e) {
            throw new AutoDeregisterException(e);
        }

    }
}
